<?php

namespace App\Http\Controllers\Auth;

use Validator;
use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use \App\Rules\StrongPassword as StrongPassword;
use \App\Model\JSONResponse as CodeBaseResponse;

class ForgotPasswordController extends Controller
{
    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('guest');
    }

    /**
     * 验证函数
     *
     * @param array $data 待验证数据
     *
     * @return Validator
     *
     * @var \Illuminate\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'id' => 'required',
            'phone' => [
                'bail',
                'required',
                'string',
                'size:11',
                'regex:/\d/',
                Rule::unique('users')->ignore($data['id']),
            ],
            'password' => [
                'required',
                'min:6',
                'max:512',
                // 'confirmed',
                'same:password_confirmation',
                new StrongPassword,
            ],
        ]);
    }

    /**
     * 忘记密码配置
     *
     * @param data 用户数据
     * @return json
     */
    public function index(Request $request)
    {
        $data = $request->only(['id', 'phone', 'password', 'password_confirmation']);
        $validator = $this->validator($data);
        if ($validator->fails()) {
            return response()->json(CodeBaseResponse::error($validator->errors()));
        }
        $user = User::where('phone', $data['phone'])->first();

        // 其他方式验证（在Validator完成）
        if (!$user) {
            return response()->json(CodeBaseResponse::resetError());
        }
        $user->password = Hash::make($data['password']);
        $updated = $user->save();
        if ($updated) {
            return response()->json(CodeBaseResponse::success());
        }
        return response()->json(CodeBaseResponse::resetError('check success, updated failed'));
    }
}
